<template>
  <div class="container">
    <van-nav-bar fixed left-arrow @click-left="$router.back()" title="小智同学"></van-nav-bar>
    <!-- 聊天列表 -->
    <div class="chat-list" ref="list">
      <!-- 聊天对象A-小智同学 -->
      <!-- 动态渲染 -->
      <div class="chat-item " :class="{left:item.name==='xz' , right:item.name==='self'}" v-for="(item,i) in list" :key="i">
        <van-image v-if="item.name==='xz'" fit="cover" round :src="xzTx" />
        <div class="chat-pao">{{item.msg}}</div>
        <van-image v-if="item.name==='self'" fit="cover" round :src="photo" />
      </div>
      <!-- 聊天对象B-当前登录人 -->
      <!-- <div class="chat-item right">
        <div class="chat-pao">ewqewq</div>
        <van-image fit="cover" round src="https://img.yzcdn.cn/vant/cat.jpeg" />
      </div> -->
    </div>
    <div class="reply-container van-hairline--top">
      <van-field v-model="value" placeholder="说点什么...">
        <span @click="send()" slot="button" style="font-size:12px;color:#999">提交</span>
      </van-field>
    </div>
  </div>
</template>

<script>
// 引入本地图片
/**
 * 1、通过 import 导入
 * 2、通过 require 导入
 */
import xzTx from '../../assets/xz.jpg'
import { mapGetters, mapState } from 'vuex'
import io from 'socket.io-client'
// const selfTx = require('../../assets/xz.jpg')
export default {
  data () {
    return {
      // 聊天数据
      // name: 聊天对象； msg: 聊天内容
      // 设置数据结构：[{name:'xz',msg:'你好!'},{name:'self',msg:'你好!小智'}]
      list: [],
      // 聊天内容
      value: '',
      // 小智头像
      xzTx
    }
  },
  created () {
    this.createWs()
  },
  computed: {
    ...mapState(['user']),
    // 重新获取用户的头像信息，还是透过hash传入
    ...mapGetters(['photo'])
  },
  methods: {
    // 内容超过一屏滚动到最底部
    goBottom () {
      this.$nextTick(() => {
        this.$refs.list.scrollTop = this.$refs.list.scrollHeight
      })
    },
    send () {
      // this.list.push({ name: 'self', msg: this.value })
      // // 向服务器发消息
      // this.ws.send(this.value)
      // this.value = ''
      this.socket.emit('message', { name: 'self', msg: this.value, timestamp: Date.now() })
      this.list.push({ name: 'self', msg: this.value })
      this.value = ''
    },
    // 原生webscoket
    createWs () {
      //   /**
      //    * webSocket用法=》类似打电话场景
      //    * 1、建立连接（拨号）
      //    * 2、通话（双向）
      //    * 3、通话结束，断开连接（挂电话）
      //    */
      //   // 建立连接=》创建ws实例
      //   this.ws = new WebSocket('wss://echo.websocket.org0')
      //   this.ws.onopen = () => {
      //     console.log('连接建立成功')
      //     // 客户端向服务端发送数据
      //     this.ws.send(Math.random() * 100)
      //   }
      //   this.ws.onmessage = (e) => {
      //     console.log('服务器发送的数据:', e.data)
      //     // 小智显示的数据
      //     this.list.push({ name: 'xz', msg: e.data })
      //   }
      //   this.ws.onclose = () => {
      //     console.log('ws关闭了')
      //   }
      try {
        this.socket = io('http://localhost:3000', {
          transports: ['websocket'],
          query: {
            token: this.user.token
          }
        })
        this.socket.on('connect', () => {
          // 建了链接后默认  小智给你打招呼
          this.list.push({ name: 'xz', msg: '你好' })
        })
        this.socket.on('message', data => {
          // 接受机器人消息
          this.list.push({ name: 'xz', msg: data.msg })
          // 滚动到底部
          this.goBottom()
        })
      } catch (error) {
        console.log(error)
      }
    }
  },
  beforeDestroy () {
    // 关闭ws连接
    this.socket.close()
  }
}
</script>

<style scoped lang='less'>
.container {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  box-sizing: border-box;
  background: #fafafa;
  padding: 46px 0 50px 0;
  .chat-list {
    height: 100%;
    overflow-y: scroll;
    .chat-item {
      padding: 10px;
      .van-image {
        vertical-align: top;
        width: 40px;
        height: 40px;
      }
      .chat-pao {
        vertical-align: top;
        display: inline-block;
        min-width: 40px;
        max-width: 70%;
        min-height: 40px;
        line-height: 38px;
        border: 0.5px solid #c2d9ea;
        border-radius: 4px;
        position: relative;
        padding: 0 10px;
        background-color: #e0effb;
        word-break: break-all;
        font-size: 14px;
        color: #333;
        &::before {
          content: "";
          width: 10px;
          height: 10px;
          position: absolute;
          top: 12px;
          border-top: 0.5px solid #c2d9ea;
          border-right: 0.5px solid #c2d9ea;
          background: #e0effb;
        }
      }
    }
  }
}
.chat-item.right {
  text-align: right;
  .chat-pao {
    margin-left: 0;
    margin-right: 15px;
    &::before {
      right: -6px;
      transform: rotate(45deg);
    }
  }
}
.chat-item.left {
  text-align: left;
  .chat-pao {
    margin-left: 15px;
    margin-right: 0;
    &::before {
      left: -5px;
      transform: rotate(-135deg);
    }
  }
}
.reply-container {
  position: fixed;
  left: 0;
  bottom: 0;
  height: 44px;
  width: 100%;
  background: #f5f5f5;
  z-index: 9999;
}
</style>
